#include "urlsniffer.h"
#include "appglobal.h"
#include "diskmap.h"
#include "sniffer.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QRegExp>
#include <QDebug>

void YDUrlSniffer::sniff(const YDUrlSniffer::job_t& job) {
    this->successCount = 0;
    this->errorCount = 0;
    this->count = 0;
    this->resultsMap.clear();

    for (auto p : job) {
        YDSniffer* sniffer = g.diskMap->getSniffer(p.first, this);

        if (sniffer) {
            connect(sniffer, &YDSniffer::error, this, &YDUrlSniffer::on_sniffer_error);
            connect(sniffer, &YDSniffer::getUrl, this, &YDUrlSniffer::on_sniffer_getUrl);
            sniffer->sniff(p.second);
            this->count += p.second.size();
        }
    }
}

void YDUrlSniffer::on_sniffer_getUrl(const QString& url, const QString& realUrl) {
    YDSniffer* sniffer = reinterpret_cast<YDSniffer*>(this->sender());
    if (this->resultsMap.find(sniffer->type()) == this->resultsMap.end()) {
        QList<QPair<QString, QString>> lst = {QPair<QString, QString>(url, realUrl)};
        this->resultsMap[sniffer->type()] = lst;
    } else {
        this->resultsMap[sniffer->type()].append(QPair<QString, QString>(url, realUrl));
    }

    this->successCount++;

    emit this->progressChanged(this->progress());
    if (this->isFinished()) {
        emit this->finished();
    }
}

void YDUrlSniffer::on_sniffer_error(const QString& url) {
    YDSniffer* sniffer = reinterpret_cast<YDSniffer*>(this->sender());
    if (this->resultsMap.find(sniffer->type()) == this->resultsMap.end()) {
        QList<QPair<QString, QString>> lst = {QPair<QString, QString>(url, "")};
        this->resultsMap[sniffer->type()] = lst;
    } else {
        this->resultsMap[sniffer->type()].append(QPair<QString, QString>(url, ""));
    }

    this->errorCount++;
    emit this->progressChanged(this->progress());
    if (this->isFinished()) {
        emit this->finished();
    }
}
